package com.tarena.lbs.activity.service.impl;

import com.alibaba.nacos.common.utils.CollectionUtils;
import com.github.pagehelper.PageInfo;
import com.tarena.lbs.activity.dao.repository.ActivityRepository;
import com.tarena.lbs.activity.pojo.param.ActivityAddParam;
import com.tarena.lbs.activity.pojo.po.ActivityPO;
import com.tarena.lbs.activity.pojo.query.ActivityQuery;
import com.tarena.lbs.activity.pojo.vo.ActivityVO;
import com.tarena.lbs.activity.service.ActivityService;
import com.tarena.lbs.attach.api.AttachApi;
import com.tarena.lbs.attach.pojo.dto.AttachDTO;
import com.tarena.lbs.attach.pojo.query.AttachQuery;
import com.tarena.lbs.base.protocol.exception.BusinessException;
import com.tarena.lbs.base.protocol.pager.PageResult;
import com.tarena.lbs.common.principle.UserPrinciple;
import com.tarena.lbs.common.utils.AuthenticationContextUtils;
import com.tarena.lbs.user.api.UserApi;
import com.tarena.lbs.user.api.pojo.dto.AdminDto;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.StringJoiner;

@Slf4j
@Service
public class ActivityServiceImpl implements ActivityService {
    @Autowired
    private ActivityRepository activityRepository;
    @DubboReference
    private UserApi userApi;
    @DubboReference
    private AttachApi attachApi;
    @Value("${url.prefix}")
    private String urlPrefix;

    @Override
    public PageResult<ActivityVO> pageList(ActivityQuery query) throws BusinessException {
        log.debug("分页查询商家活动业务,query={}", query);
        // 获取当前登录用户
        UserPrinciple userPrinciple = AuthenticationContextUtils.get();
        log.debug("分页查询商家活动业务,userPrinciple={}", userPrinciple);
        if (userPrinciple == null) {
            throw new BusinessException("-2","用户未登录");
        }
        Integer userId = userPrinciple.getId();
        // 调用 UserApi 校验商家是否存在
        AdminDto adminDto = userApi.getAdminById(userId);
        if (adminDto == null) {
            throw new BusinessException("-3","商家不存在");
        }
        Integer businessId = adminDto.getBusinessId();
        query.setBusinessId(businessId);
        // 调用 ActivityRepository 查询活动列表
        PageInfo<ActivityPO> pageInfo = activityRepository.pageListByBusinessId(query);
        // 转换为 PageResult<ActivityVO>
        PageResult<ActivityVO> pageResult = new PageResult<>();
        pageResult.setPageNo(pageInfo.getPageNum());
        pageResult.setPageSize(pageInfo.getPageSize());
        pageResult.setTotal(pageInfo.getTotal());
        List<ActivityPO> pos = pageInfo.getList();
        List<ActivityVO> vos = null;
        if (CollectionUtils.isNotEmpty(pos)) {
            vos = new ArrayList<>();
            for (ActivityPO po : pos) {
                ActivityVO vo = new ActivityVO();
                BeanUtils.copyProperties(po, vo);
                vos.add(vo);
            }
        }
        pageResult.setObjects(vos);
        log.debug("分页查询商家活动业务,pageResult={}", pageResult);
        return pageResult;
    }

    @Override
    public void activitySave(ActivityAddParam param) throws BusinessException {
        log.debug("保存活动业务,param={}", param);
        Integer id = param.getId();
        if (id == null) {
            // 新增
            ActivityPO po = new ActivityPO();
            BeanUtils.copyProperties(param, po);
            po.setCreateAt(new Date());
            log.debug("保存活动业务-新增,po={}", po);
            activityRepository.insert(po);
        } else {
            // 更新
            ActivityPO po = activityRepository.selectActivityById(id);
            if (po == null) {
                throw new BusinessException("-4","活动不存在");
            }
            BeanUtils.copyProperties(param, po);
            po.setUpdateAt(new Date());
            log.debug("保存活动业务-更新,po={}", po);
            activityRepository.updateById(po);
        }
    }

    @Override
    public ActivityVO activityDetail(Integer id) {
        log.debug("查询活动详情业务,id={}", id);
        ActivityPO po = activityRepository.selectActivityById(id);
        if (po == null) {
            return null;
        }
        ActivityVO vo = new ActivityVO();
        BeanUtils.copyProperties(po, vo);
        log.debug("查询活动详情业务,vo={}", vo);
        AttachQuery attachQuery = new AttachQuery();
        attachQuery.setBusinessId(po.getBusinessId());
        List<AttachDTO> imgPicDTOs = attachApi.getAttachInfo(attachQuery);
        if (CollectionUtils.isNotEmpty(imgPicDTOs)) {
            List<String> imgPics = new ArrayList<>();
            StringJoiner stringJoiner = new StringJoiner(",");
            for (AttachDTO imgPicDTO : imgPicDTOs) {
                imgPics.add(urlPrefix + imgPicDTO.getFileUuid());
                stringJoiner.add(imgPicDTO.getId().toString());
            }
            vo.setImgPics(imgPics);
            vo.setImgIds(stringJoiner.toString());
        }
        return vo;
    }
}
